package register

import (
	"sync/atomic"
	"time"

	"gitee.com/fanshuaiself/sidecar/nacos"
	"gitee.com/fanshuaiself/sidecar/util"
	log "github.com/sirupsen/logrus"
)

type RegisterPlugin struct {
	healthChecker HealthChecker
	checkInterval time.Duration
	health bool
	running int32
	closeFn func()
}

func (r *RegisterPlugin) Initialize(config *util.Config, closeFunc func()) {
	r.checkInterval = config.HeartBeatInterval
	r.closeFn = closeFunc
	r.healthChecker = newHttpChecker(config)
	r.health = false
}

func (r *RegisterPlugin) Start() error {
	if atomic.CompareAndSwapInt32(&r.running, 0, 1) {
		go r.doStart()
	}
	return nil
}

func (r *RegisterPlugin) Stop () {
	if atomic.CompareAndSwapInt32(&r.running, 1, 0) {
		nacos.DeRegister()
	}
}

func (r *RegisterPlugin) doStart() {
	log.Print("register启动")
	r.checkAndRegister()

	for atomic.LoadInt32(&r.running) == 1 {
		<- time.After(r.checkInterval)
		r.checkAndRegister()
	}

	nacos.DeRegister()
	log.Print("register停止")
}

func (r *RegisterPlugin) checkAndRegister() {
	health := r.healthChecker.IsHealth()
	if health == r.health {
		return
	}

	r.health = health
	if health {
		nacos.Register(true)
	} else {
		nacos.DeRegister()
	}
}